<template>
  <view class="edit-wrapper">
    <view class="wrapper-scroll">
      <uni-forms class="cust-form" ref="form" :modelValue="form" :rules="rules" label-position="top">
        <view class="view-block mb-50">
          <uni-forms-item name="workName">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业名称</text>
              </view>
            </template>
            <uni-easyinput v-model="form.workName" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="workTypeId">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业类型</text>
              </view>
            </template>
            <uni-data-select v-model="form.workTypeId" :localdata="safetyManagementList" @change="workTypeChange" placeholder="请选择..." :disabled="sbDisabled"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item name="location">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业地点</text>
              </view>
            </template>
            <uni-easyinput v-model="form.location" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="workTime">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业时间</text>
              </view>
            </template>
            <uni-datetime-picker type="date" v-model="form.workTime" placeholder="请选择..." :disabled="sbDisabled" />
          </uni-forms-item>
          <uni-forms-item name="estimatedDuration">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">预计时长</text>
              </view>
            </template>
            <uni-easyinput v-model="form.estimatedDuration" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="responsiblePerson">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业负责人</text>
              </view>
            </template>
            <uni-easyinput v-model="form.responsiblePerson" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="contactPhone">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">联系方式</text>
              </view>
            </template>
            <uni-easyinput v-model="form.contactPhone" placeholder="请输入..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item name="workContent">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">作业内容</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.workContent" placeholder="请输入具体流程、设备及工具、作业环境描述..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="riskAssessment">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">风险评估</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.riskAssessment" placeholder="请输入需要评估风险信息..." :disabled="sbDisabled"></uni-easyinput>
          </uni-forms-item>

          <uni-forms-item>
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">附件上传</text>
              </view>
            </template>

            <uni-file-picker
              class="cust-file-upload"
              v-model="fileList"
              :custSty="true"
              :auto-upload="false"
              file-mediatype="all"
              file-extname="jpeg,jpg,png,doc,docx,pdf,dwg"
              :list-styles="uploadListSty"
              @select="fileOnSelect"
              :disabled="sbDisabled"
              :class="{ hideuploadSty: sbDisabled }"
              @custPreview="preview"
            >
              <view class="cust-file-upload-btn">
                <image class="upload-icon" src="/static/images/common/file-upload.png" mode=""></image>
                <text class="upload-title">上传附件</text>
                <text class="upload-subtitle">上传word、pdi、png、jpeg、dwg文件,且每个文件大小不超过50MB</text>
              </view>
            </uni-file-picker>
          </uni-forms-item>
        </view>

        <view class="mb-50 view-block2">
          <uni-collapse v-model="activeNames">
            <uni-collapse-item title-border="none" :border="false">
              <template v-slot:title>
                <uni-section title="应对措施" type="line" titleColor=" #102C59" titleFontSize="32rpx"></uni-section>
              </template>
              <view class="view-block">
                <uni-forms-item name="safetyProtection">
                  <template #label>
                    <view class="cust-form-lab">
                      <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                      <text class="lab">安全措施</text>
                    </view>
                  </template>
                  <uni-easyinput type="textarea" v-model="form.safetyProtection" disabled></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item name="emergencyMeasures">
                  <template #label>
                    <view class="cust-form-lab">
                      <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                      <text class="lab">应急措施</text>
                    </view>
                  </template>
                  <uni-easyinput type="textarea" v-model="form.emergencyMeasures" disabled></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item name="riskControl">
                  <template #label>
                    <view class="cust-form-lab">
                      <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                      <text class="lab">风险措施</text>
                    </view>
                  </template>
                  <uni-easyinput type="textarea" v-model="form.riskControl" disabled></uni-easyinput>
                </uni-forms-item>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>

        <view class="mb-50 view-block" v-if="dialogType != 1 || (form.id && form.rejectReason)">
          <uni-forms-item name="riskControl">
            <template #label>
              <view class="cust-form-lab">
                <image class="lab-icon" src="/static/images/fillout/list-tip.png" mode=""></image>
                <text class="lab">审批意见</text>
              </view>
            </template>
            <uni-easyinput type="textarea" v-model="form.rejectReason" placeholder="请输入..." :disabled="adviceDisabled"></uni-easyinput>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>
    <view class="fixed-btn-box">
      <template v-if="dialogType == 2">
        <view class="cust-btn" @click="submitForm(2)">通过</view>
        <view class="cust-btn danger" @click="submitForm(3)">驳回</view>
      </template>
      <view v-else-if="dialogType == 1" class="cust-btn" @click="submitForm(1)">提交填报</view>
      <view v-else-if="dialogType == 3" class="cust-btn" @click="goBack()">返回</view>
    </view>

    <msg-popup ref="msgPopup">
      <template #content>
        <view class="cust-msg-content">
          <view class="title">提示信息</view>
          <view class="msg">{{ popMsg }}</view>
        </view>
      </template>
    </msg-popup>
  </view>
</template>

<script>
import { required } from '@/utils/rules';
import { listAllSafetyManagement } from '@/api/person/safetyManagement';
import { getPreReportRecords, addPreReportRecords, updatePreReportRecords, examPreReportRecords } from '@/api/person/preReportRecords';
import { uploadFiles } from '@/api/system/common.js';
import config from '@/config';

export default {
  data() {
    return {
      popMsg: '',
      id: null,
      form: {},
      rules: {
        workName: { rules: [required('作业名称不能为空')] },
        workTypeId: { rules: [required('作业类型不能为空')] },
        location: { rules: [required('作业地点不能为空')] },
        workTime: { rules: [required('作业时间不能为空')] },
        estimatedDuration: { rules: [required('预计时长不能为空')] },
        responsiblePerson: { rules: [required('作业负责人不能为空')] },
        contactPhone: { rules: [required('联系方式不能为空')] },
        workContent: { rules: [required('作业内容不能为空')] },
        riskAssessment: { rules: [required('作业内容不能为空')] }
      },
      safetyManagementList: [],
      dialogType: 1, // 1:申请 2:审核 3:详情
      sbDisabled: false,
      adviceDisabled: false,
      activeNames: [],
      fileList: [],
      maxSize: 50 * 1024 * 1024,
      uploadListSty: { dividline: false, border: false },
      baseFileUrl: config.baseFileUrl
    };
  },
  onLoad(option) {
    this.getSafeList();
    if (option && option.id) {
      if (option.type) {
        this.dialogType = option.type;
        this.sbDisabled = option.type == 2 || option.type == 3;
        this.adviceDisabled = option.type == 2 ? false : true;
      }
      this.handleData(option.id);
    }
  },
  methods: {
    getSafeList() {
      listAllSafetyManagement().then((response) => {
        let tempList = response.data;
        this.safetyManagementList = tempList.map((item) => {
          return {
            ...item,
            text: item.workTypeName,
            value: item.id
          };
        });
      });
    },
    handleData(id) {
      getPreReportRecords(id).then((response) => {
        const data = response.data;
        this.form = data;
        if (this.dialogType == 2) {
          this.form.rejectReason = null;
        }
        this.workTypeChange(data.workTypeId);
        if (data.preReportAttachments && data.preReportAttachments.length) {
          this.fileList = data.preReportAttachments.map((item) => {
            return {
              id: item.id,
              name: item.fileName,
              url: this.baseFileUrl + item.fileUrl,
              extname: item.fileType
            };
          });
        }
      });
    },
    workTypeChange(val) {
      if (val) {
        for (let i = 0; i < this.safetyManagementList.length; i++) {
          let item = this.safetyManagementList[i];
          if (item.id == val) {
            this.form.safetyProtection = item.safetyProtection;
            this.form.emergencyMeasures = item.emergencyMeasures;
            this.form.riskControl = item.riskControl;
            break;
          }
        }
      } else {
        this.form.safetyProtection = null;
        this.form.emergencyMeasures = null;
        this.form.riskControl = null;
      }
    },
    submitForm(type) {
      if (type == 1) {
        this.form.status = 1;
        this.$refs.form.validate().then((res) => {
          if (!this.fileList.length) {
            return this.custPop('请上传附件');
          }
          this.uploadFilesLoop();
        });
        return;
      } else {
        this.exam(type);
      }
    },
    exam(type) {
      if (type == 3) {
        if (this.form.rejectReason == null || this.form.rejectReason == '') {
          this.custPop('审批意见不能为空');
          return;
        }
        this.form.status = 3;
      } else {
        this.form.status = 2;
      }

      let params = {
        id: this.form.id,
        status: this.form.status,
        rejectReason: this.form.rejectReason
      };
      examPreReportRecords(params).then((response) => {
        this.navPop('操作成功');
      });
    },
    fileOnSelect(e) {
      const files = e.tempFiles || e.tempFilePaths || [];
      const tempFiles = files.filter((f) => {
        const ok = (f.size || 0) <= this.maxSize;
        if (!ok) {
          uni.showToast({
            title: '文件不能超过50MB',
            icon: 'none'
          });
        }
        return ok;
      });
      this.fileList = [...this.fileList, ...tempFiles];
    },
    async uploadFilesLoop() {
      this.form.preReportAttachments = [];
      for (var i = 0; i < this.fileList.length; i++) {
        let item = this.fileList[i];
        if (item.id) {
          this.form.preReportAttachments.push({
            id: item.id,
            fileName: item.name,
            fileUrl: item.url
          });
        } else {
          let filePath = item.url || item;
          let params = { name: 'files', filePath: filePath };
          let res = await uploadFiles(params);
          if (res.code == 200) {
            this.form.preReportAttachments.push({
              fileName: res.newFileNames,
              fileUrl: res.urls
            });
          }
          // uploadFiles(params).then((res) => {
          //   this.form.preReportAttachments.push({
          //     fileName: res.newFileNames,
          //     fileUrl: res.urls
          //   });
          // }).catch((err) => {
          //    console.log(err);
          // });
        }
      }

      this.applyFn();
    },
    applyFn() {
      if (this.form.id != null) {
        updatePreReportRecords(this.form).then((response) => {
          this.navPop('修改成功');
        });
      } else {
        addPreReportRecords(this.form).then((response) => {
          this.navPop('申请成功');
        });
      }
    },
    preview(item) {
      if (['png', 'jpg', 'jpeg'].includes(item.extname)) {
        uni.previewImage({
          // current: 0,
          urls: [item.url] // 需要预览的图片url列表数组
        });
      } else if(['pdf'].includes(item.extname)){
        uni.setStorageSync('previewUrl', item.url);
        this.$tab.navigateTo('/pages/preview/preview')
        
      }else {
        uni.downloadFile({
          url: item.url,
          success: (downloadRes) => {
            if (downloadRes.statusCode === 200) {
              const filePath = downloadRes.tempFilePath;
              // #ifdef H5
              const link = document.createElement('a');
              link.href = filePath;
              link.download = item.name;
              link.click();
              link.remove();
              // #endif

              // #ifndef H5
              uni.openDocument({
                filePath: filePath,
                success: () => {
                  console.log('文件预览成功');
                }
              });
              // #endif
            }
          }
        });
      }
    },
    goBack() {
      this.$tab.navigateBack();
    },
    navPop(msg) {
      this.popMsg = msg;
      this.$refs.msgPopup.open();
      setTimeout(() => {
        this.$tab.navigateBack();
      }, 900);
    },
    custPop(msg) {
      this.popMsg = msg;
      this.$refs.msgPopup.open();
      setTimeout(() => {
        this.$refs.msgPopup.close();
      }, 800);
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-wrapper {
  height: 100%;

  .wrapper-scroll {
    height: calc(100% - 114rpx);
    overflow-y: auto;
  }

  .view-block {
    background: #fff;
    padding: 30rpx;
  }

  ::v-deep .view-block2 {
    .uni-textarea-textarea {
      color: #102c59;
      font-size: 26rpx;
    }
  }
}
.mb-50 {
  margin-bottom: 50rpx;
}
.cust-msg-content {
  text-align: center;
  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #000000;
    line-height: 72rpx;
    padding-top: 180rpx;
  }
  .msg {
    font-size: 32rpx;
    font-weight: 500;
    color: #000000;
    line-height: 64rpx;
  }
}

.danger {
  margin-left: 30rpx;
}

::v-deep .uni-section .uni-section-header {
  padding: 20rpx 30rpx;
}
::v-deep .uni-section__content-title {
  font-weight: 500;
}

.cust-file-upload {
  &-btn {
    width: 100%;
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    border: 1px solid #2e7dff;
    padding: 20rpx 32rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .upload-icon {
      width: 44rpx;
      height: 44rpx;
    }
    .upload-title {
      font-weight: 500;
      font-size: 32rpx;
      color: #2e7dff;
      padding-top: 10rpx;
    }

    .upload-subtitle {
      font-weight: 500;
      font-size: 20rpx;
      color: rgba(46, 125, 255, 0.5);
    }
  }
  /deep/.file-picker__progress {
    display: none;
  }
}
.cust-file-upload.hideuploadSty {
  ::v-deep .files-button,
  ::v-deep.icon-del-box {
    display: none;
  }
  ::v-deep.files__name {
    margin-right: 0;
  }
}
</style>
